<template>
  <div class="login-page">
    <div class="login-dialog">
      <div class="login-dialog-content">
        <div class="logo-section">
          <IconDeepseekText class="logo-svg" />
        </div>
        <div class="login-panel">
          <div class="form-content">
            <div class="login-tabs">
              <div
                tabindex="0"
                class="tab-button"
                :class="{ 'active': activeTab === 'code' }"
                @click="activeTab = 'code'"
              >
                验证码登录
                <div v-if="activeTab === 'code'" class="active-tab-indicator"></div>
              </div>
              <div
                tabindex="0"
                class="tab-button"
                :class="{ 'active': activeTab === 'password' }"
                @click="activeTab = 'password'"
              >
                密码登录
                <div v-if="activeTab === 'password'" class="active-tab-indicator"></div>
              </div>
            </div>
            <div class="login-notice">你所在地区仅支持 手机号 / 邮箱 登录</div>

            <div v-if="activeTab === 'code'">
              <div class="input-group">
                <div class="input-wrapper">
                  <div class="input-prefix">
                    <IconPhone class="icon-phone" />
                  </div>
                  <span class="country-code-label">+86</span>
                  <input
                    type="tel"
                    placeholder="请输入手机号"
                    class="form-input phone-number-input"
                    v-model="phoneNumber"
                  />
                </div>
                <div class="form-message">{{ phoneNumberError }}</div>
              </div>

              <div class="input-group">
                <div class="code-input-container">
                  <div class="input-wrapper">
                    <div class="input-prefix">
                      <IconVerificationCode class="icon-code" />
                    </div>
                    <input
                      maxlength="6"
                      type="tel"
                      placeholder="请输入验证码"
                      class="form-input verification-code-input"
                      v-model="verificationCode"
                    />
                  </div>
                  <button type="button" class="button button-outline send-code-button" @click="sendCode" :disabled="isSendingCode">
                    {{ sendCodeButtonText }}
                  </button>
                </div>
                <div class="form-message">{{ verificationCodeError }}</div>
              </div>
            </div>

            <div v-else-if="activeTab === 'password'">
              <div class="input-group">
                <div class="input-wrapper">
                  <div class="input-prefix">
                    <IconEmail class="icon-form" />
                  </div>
                  <input
                    type="text"
                    placeholder="请输入手机号/邮箱地址"
                    class="form-input"
                    v-model="loginAccount"
                  />
                </div>
                <div class="form-message"></div>
              </div>

              <div class="input-group">
                <div class="input-wrapper">
                  <div class="input-prefix">
                    <IconLock class="icon-form" />
                  </div>
                  <input
                    :type="passwordFieldType"
                    placeholder="请输入密码"
                    class="form-input"
                    v-model="password"
                  />
                  <div class="password-toggle" tabindex="0" @click="togglePasswordVisibility">
                    <IconEye class="icon-form" />
                  </div>
                </div>
                <div class="form-message"></div>
              </div>
            </div>

            <div class="agreement-section">
              <p class="agreement-text">
                注册登录即代表已阅读并同意我们的
                <a
                  href="https://cdn.deepseek.com/policies/zh-CN/deepseek-terms-of-use.html"
                  target="_blank"
                  rel="noopener noreferrer"
                  class="link agreement-link"
                >
                  用户协议
                </a>
                与
                <a
                  href="https://cdn.deepseek.com/policies/zh-CN/deepseek-privacy-policy.html"
                  target="_blank"
                  rel="noopener noreferrer"
                  class="link agreement-link"
                >
                  隐私政策
                </a>
                ，未注册的手机号将自动注册
              </p>
            </div>

            <button type="button" class="button button-primary login-button" @click="handleLogin">登录</button>

            <div class="password-login-actions" v-if="activeTab === 'password'">
              <div tabindex="0" role="button" class="action-button">忘记密码</div>
              <div tabindex="0" role="button" class="action-button" @click="goToRegister">立即注册</div>
            </div>


          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onUnmounted } from 'vue';
import { useUserStore } from '@/store/user';
import { useRouter } from 'vue-router';
import IconDeepseekText from '@/components/icons/IconDeepseekText.vue';
import IconPhone from '@/components/icons/IconPhone.vue';
import IconVerificationCode from '@/components/icons/IconVerificationCode.vue';
import IconEmail from '@/components/icons/IconEmail.vue';
import IconLock from '@/components/icons/IconLock.vue';
import IconEye from '@/components/icons/IconEye.vue';
import { validatePhoneNumber, validateEmail, validateAccount } from '@/util';
import {
  sendLoginOtp,
  verifyLoginOtp,
  loginWithPassword,
  currentUser,
  isLoading,
  errorMessage
} from '@/types/api';

const router = useRouter();

// State for active tab and form inputs
const activeTab = ref('code'); // 'code' for verification code, 'password' for password login
const phoneNumber = ref('');
const verificationCode = ref('');
const loginAccount = ref(''); // For password login: phone number or email
const password = ref('');
const showPassword = ref(false); // To toggle password visibility

// Error message states
const phoneNumberError = ref('');
const verificationCodeError = ref('');

// Send code button state
const isSendingCode = ref(false);
const sendCodeButtonText = ref('发送验证码');
let countdownTimer = null;

// Computed property for password input type
const passwordFieldType = computed(() => (showPassword.value ? 'text' : 'password'));

// Methods
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

const validatePhoneNumberInput = () => {
  if (!phoneNumber.value) {
    phoneNumberError.value = '请输入手机号';
    return false;
  }

  if (!validatePhoneNumber(phoneNumber.value)) {
    phoneNumberError.value = '请输入正确的手机号格式';
    return false;
  }

  phoneNumberError.value = '';
  return true;
};

const sendCode = async () => {
  if (!validatePhoneNumberInput()) return;
  if (isSendingCode.value) return;

  isSendingCode.value = true;
  sendCodeButtonText.value = '发送中...';
  
  try {
    const success = await sendLoginOtp({ phone_number: phoneNumber.value });
    if (success) {
      let countdown = 60;
      sendCodeButtonText.value = `${countdown}s后重发`;
      countdownTimer = setInterval(() => {
        countdown--;
        if (countdown <= 0) {
          clearInterval(countdownTimer);
          sendCodeButtonText.value = '发送验证码';
          isSendingCode.value = false;
        } else {
          sendCodeButtonText.value = `${countdown}s后重发`;
        }
      }, 1000);
    }
  } catch (error) {
    console.error('Failed to send verification code:', error);
    verificationCodeError.value = errorMessage.value || '验证码发送失败，请稍后重试';
    sendCodeButtonText.value = '发送验证码';
    isSendingCode.value = false;
  }
};

// 添加账号验证
const validateLoginAccount = () => {
  if (!loginAccount.value) {
    return { valid: false, message: '请输入手机号或邮箱' };
  }

  if (!validateAccount(loginAccount.value)) {
    return { valid: false, message: '请输入正确的手机号或邮箱格式' };
  }

  return { valid: true, message: '' };
};

const handleLogin = async () => {
  if (activeTab.value === 'code') {
    if (!validatePhoneNumberInput()) return;
    if (!verificationCode.value) {
      verificationCodeError.value = '请输入验证码';
      return;
    }

    try {
      const user = await verifyLoginOtp({
        phone_number: phoneNumber.value,
        otp: verificationCode.value
      });
      if (user) {
        const userStore = useUserStore();
        userStore.setUser(user);
        router.push('/');
      }
    } catch (error) {
      verificationCodeError.value = errorMessage.value || '登录失败，请检查验证码';
    }
  } else if (activeTab.value === 'password') {
    const accountValidation = validateLoginAccount();
    if (!accountValidation.valid) {
      verificationCodeError.value = accountValidation.message;
      return;
    }

    if (!password.value) {
      verificationCodeError.value = '请输入密码';
      return;
    }

    try {
      const user = await loginWithPassword({
        identifier: loginAccount.value,
        password: password.value
      });
      if (user) {
        const userStore = useUserStore();
        userStore.setUser(user);
        router.push('/');
      }
    } catch (error) {
      verificationCodeError.value = errorMessage.value || '登录失败，请检查账号和密码';
    }
  }
};

const goToRegister = () => {
  console.log('Navigating to register page');
  router.push('/register');
};

// Clear countdown on component unmount
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
});
</script>

<style lang="scss" scoped>
// Variables
$primary-color: #4D6BFE;
$text-primary: #262626; // Approx rgb(38,38,38)
$text-secondary: #404040; // Approx rgb(64,64,64)
$text-muted: #a3a3a3; // Approx rgb(163,163,163)
$text-light: #8b8b8b; // Approx rgb(139,139,139)
$border-color: #e5e5e5; // Approx rgb(229,229,229)
$white: #fff;
$font-family-base: 'DeepSeek-CJK-patch', Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Noto Sans", Ubuntu, Cantarell, "Helvetica Neue", Oxygen, "Open Sans", sans-serif;

// Base Page Setup
.login-page {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding-top: 4px; // Original body padding
  font-family: $font-family-base;
  background-color: $white;
  font-size: 14px;
  line-height: 1.5; // Default line height

  // Mobile Adaptation
  @media (max-width: 768px) {
    justify-content: flex-start; // Align to top on smaller screens
    padding: 20px; // Add some general padding
    background-color: $white; // Keep background white for mobile
  }
}

.login-dialog-content {
  padding-top: 48px;

  @media (max-width: 768px) {
    padding-top: 0; // Remove top padding on mobile
    width: 100%; // Take full width
  }
}

.logo-section {
  display: flex;
  justify-content: center;
  margin-bottom: 40px;
  .logo-svg {
    height: 44px;
    width: auto; // Maintain aspect ratio
  }

  @media (max-width: 768px) {
    margin-bottom: 30px; // Adjust margin for mobile
    .logo-svg {
      height: 36px; // Smaller logo on mobile
    }
  }
}

.login-panel {
  border-radius: 16px;
  box-shadow: 0 0 1px 0 rgba(0, 0, 0, 0.2), 0 0 4px 0 rgba(0, 0, 0, 0.02), 0 12px 36px 0 rgba(0, 0, 0, 0.06);
  padding: 12px; // Outer padding for the "card"
  min-height: 420px;
  background-color: $white; // Ensure card background is white

  @media (max-width: 768px) {
    box-shadow: none; // Remove shadow on mobile for a cleaner look
    padding: 0; // Remove outer padding
    min-height: auto; // Let height adjust to content
    border-radius: 0; // No border radius
    width: 100%; // Take full width
  }
}

.form-content {
  display: flex;
  flex-direction: column;
  padding: 24px 24px 16px; // Inner padding for form elements
  width: 408px; // Fixed width for the form area
  max-width: 100%; // Ensure it doesn't overflow on very small screens if panel padding is small

  @media (max-width: 768px) {
    width: auto; // Allow width to be fluid
    padding: 20px; // Adjust padding for mobile form content
  }
}

// Tabs
.login-tabs {
  display: flex;
  justify-content: center;
  margin-bottom: 32px;
  height: 32px;

  @media (max-width: 768px) {
    margin-bottom: 24px; // Adjust margin for mobile
  }

  .tab-button {
    display: flex;
    align-items: center;
    cursor: pointer;
    position: relative;
    padding: 0 3px; // Small padding for underline positioning
    color: $text-muted;
    font-weight: 500;
    transition: color 0.2s ease;

    &:not(:last-child) {
      margin-right: 30px;
    }

    &.active {
      color: $primary-color;
      font-weight: 600;

      .active-tab-indicator {
        background-color: $primary-color;
        border-top-left-radius: 3px;
        border-top-right-radius: 3px;
        height: 3px;
        position: absolute;
        bottom: 0;
        left: 0; // Adjusted to align with text better
        right: 0;
      }
    }
    &:hover:not(.active) {
      color: darken($text-muted, 15%);
    }
  }
}

.login-notice {
  color: $text-muted;
  font-size: 12px;
  line-height: 1.4;
  margin-bottom: 8px;
  padding: 0 2px;
}

// Input Fields
.input-group {
  margin-bottom: 4px; // Spacing for potential error message
}

.input-wrapper {
  display: flex;
  align-items: center;
  background-color: transparent;
  border-radius: 10px;
  height: 44px;
  padding: 0 10px;
  position: relative;
  transition: border-color 0.2s ease, box-shadow 0.2s ease;
  border: 1px solid $border-color; // Default border for definition, replacing inset shadow

  &:focus-within {
    border-color: $primary-color;
    box-shadow: 0 0 0 2px rgba($primary-color, 0.2); // Focus ring
  }

  .input-prefix {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 8px;
    color: $text-muted; // Icon color

    .icon-phone, .icon-code, .icon-form {
      width: 18px;
      height: 18px;
    }
  }
}

.country-code-label {
  color: $text-primary;
  line-height: 44px; // Align with input field
  margin-right: 8px;
  white-space: nowrap;
}

.form-input {
  flex-grow: 1;
  font-family: $font-family-base;
  font-size: 14px;
  background-color: transparent;
  caret-color: $primary-color;
  color: $text-secondary;
  border: none;
  outline: none;
  padding: 0; // Remove default padding
  height: 100%;

  &::placeholder {
    color: $text-muted;
    opacity: 1; // Ensure placeholder is visible
  }
}

.code-input-container {
  display: flex;
  align-items: center;

  .input-wrapper {
    flex-grow: 1;
    margin-right: 12px;
  }
}

.password-toggle {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  margin-left: 8px;
  color: $text-light;
  width: 18px;
  height: 18px;

  .icon-form {
    width: 18px;
    height: 18px;
    fill: currentColor;
  }
}

.form-message {
  font-size: 12px;
  line-height: 1.4;
  min-height: 21px; // Reserve space to prevent layout shifts
  padding: 2px 2px 6px; // Add some bottom padding for spacing
  color: #D32F2F; // Error color
  text-align: left;
}

// Buttons
.button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 10px;
  font-size: 14px;
  height: 44px;
  padding: 0 14px;
  text-decoration: none;
  white-space: nowrap;
  transition: background-color 0.2s ease, border-color 0.2s ease, opacity 0.2s ease;
  user-select: none;
  cursor: pointer;
  border: 1px solid transparent; // Base for all buttons
  outline: none; // Remove default browser outline

  &:active {
    opacity: 0.85; // Pressed state
  }
}

.button-outline {
  background-color: $white;
  border-color: $border-color;
  color: $text-primary;

  &:hover {
    background-color: lighten($border-color, 5%); // Slight hover for outline
    border-color: darken($border-color, 8%);
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    background-color: lighten($text-muted, 25%); // Example disabled style for outline button
    border-color: lighten($text-muted, 15%);
    color: $text-muted;
  }
}

.button-primary {
  background-color: $primary-color;
  color: $white;
  font-weight: 500;

  &:hover {
    background-color: darken($primary-color, 8%);
  }
}

.send-code-button {
  // Specific styles for send-code-button if different from generic button-outline
}

.login-button {
  width: 100%; // Full width
  margin-top: 20px; // Space above login button
}



// Agreement Section
.agreement-section {
  margin-top: 16px; // Adjusted spacing
  margin-bottom: 8px;
  .agreement-text {
    color: $text-muted;
    font-size: 12px;
    line-height: 1.5;
    margin:0; // remove default p margin

    .link.agreement-link {
      color: $text-primary;
      text-decoration: underline;
      text-underline-position: from-font;
      padding: 2px 3px;
      border-radius: 4px; // Soften edges for focus outline if any
      transition: color 0.2s ease;

      &:hover {
        color: $primary-color;
      }
        &:focus-visible { // Modern focus styling
        outline: 2px solid $primary-color;
        outline-offset: 2px;
      }
    }
  }
}

.password-login-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 12px;
  font-size: 12px;
  font-weight: 500;

  .action-button {
    color: $primary-color;
    cursor: pointer;
    padding: 4px 8px; // Add some padding for clickable area
    border-radius: 8px;
    transition: background-color 0.2s ease;

    &:hover {
      background-color: rgba($primary-color, 0.1);
    }
    &:focus-visible {
      outline: 2px solid $primary-color;
      outline-offset: 2px;
    }
  }
}

</style>